package xin.mydreams.mybill.widget.bill.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import xin.mydreams.mybill.widget.bill.entity.Bill;
import xin.mydreams.mybill.widget.bill.entity.ClassInfo;
import xin.mydreams.mybill.widget.bill.reposirtory.BillRepostory;
import xin.mydreams.mybill.widget.bill.service.IBillService;
import xin.mydreams.mybill.widget.user.entity.User;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class BillServiceImpl implements IBillService {

    @Autowired
    private BillRepostory billRepostory;

    @Override
    public Bill save(Bill bill) {
        return billRepostory.save(bill);
    }

    @Override
    public void delete(String id) {
        billRepostory.deleteById(id);
    }

    @Override
    public Page<Bill> pageList(int pageNo, int pageSize, String time) {
        Sort sort = new Sort(Sort.Direction.DESC, "createdTime");
        Pageable pageable = PageRequest.of(pageNo, pageSize, sort);
        return changeUser(billRepostory.findByCreatedTime(time, pageable));
    }

    private Page<Bill> changeUser(Page<Bill> page) {
        if (page != null) {
            List<Bill> content = page.getContent();
            if (content != null && content.size() > 0) {
                content.stream().forEach(bill -> {
                    User createdUser = bill.getCreatedUser();
                    User lastModifiedUser = bill.getLastModifiedUser();
                    if (createdUser != null) {
                        createdUser.setCreatedUser(null);
                        createdUser.setLastModifiedUser(null);
                        bill.setCreatedUser(createdUser);

                    }
                    if (lastModifiedUser != null) {
                        lastModifiedUser.setCreatedUser(null);
                        lastModifiedUser.setLastModifiedUser(null);
                        bill.setLastModifiedUser(lastModifiedUser);
                    }

                });
            }
        }

        return page;
    }

    @Override
    public Bill findById(String id) {
        return billRepostory.findById(id).get();
    }

    @Override
    public List<ClassInfo> groupByCreatedUser(String time) {
        return billRepostory.groupByCreatedUser(time);
    }


}
